<template>
  <div ref="containerRef" class="custom-table-container">
    <el-page-header :content="'【' + title + '】激活码列表'" @back="goBack" />
    <vab-query-form>
      <vab-query-form-left-panel>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel>
        <div class="stripe-panel">
          <el-checkbox v-model="stripe">斑马纹</el-checkbox>
        </div>
        <div class="border-panel">
          <el-checkbox v-model="border">边框（可拉伸列）</el-checkbox>
        </div>
        <el-button
          class="but_text"
          style="margin: 0 10px 10px 0 !important"
          text
          type="primary"
          @click="clickFullScreen"
        >
          <vab-icon
            :icon="isFullscreen ? 'fullscreen-exit-fill' : 'fullscreen-fill'"
          />
        </el-button>
        <el-popover popper-class="custom-table-radio" trigger="hover">
          <el-radio-group v-model="lineHeight">
            <el-radio label="large">大</el-radio>
            <el-radio label="default">中</el-radio>
            <el-radio label="small">小</el-radio>
          </el-radio-group>
          <template #reference>
            <el-button
              class="but_text"
              style="margin: 0 10px 10px 0 !important"
              text
              type="primary"
            >
              <vab-icon icon="line-height" />
            </el-button>
          </template>
        </el-popover>
        <el-popover popper-class="custom-table-checkbox" trigger="hover">
          <template #reference>
            <el-button
              class="but_text"
              style="margin: 0 0 10px 0 !important"
              text
              type="primary"
            >
              <vab-icon icon="settings-line" />
            </el-button>
          </template>
          <el-checkbox-group v-model="checkList">
            <vab-draggable
              v-bind="dragOptions"
              item-key="{ element }"
              :list="columns"
            >
              <template #item="{ element }">
                <div>
                  <vab-icon icon="drag-drop-line" />
                  <el-checkbox
                    :disabled="element.disableCheck === true"
                    :label="element.label"
                  >
                    {{ element.label }}
                  </el-checkbox>
                </div>
              </template>
            </vab-draggable>
          </el-checkbox-group>
        </el-popover>
      </vab-query-form-right-panel>
    </vab-query-form>
    <el-table
      v-loading="listLoading"
      :border="border"
      :data="list"
      :height="height"
      :size="lineHeight"
      :stripe="stripe"
    >
      <!--  TODO element-plus未知原因不支持拖拽后宽度重新计算，暂时放弃 -->
      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :label="item.label"
        min-width="120"
        :prop="item.prop"
        :show-overflow-tooltip="true"
        :sortable="item.sortable"
        width="auto"
      >
        <template #default="{ row }">
          <span v-if="item.prop == 'type'">
            {{ row[item.prop] == 1 ? '基础账号' : '互通账号' }}
          </span>
          <span v-else-if="item.prop == 'is_use'">
            {{ row[item.prop] == 0 ? '否' : '是' }}
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="150">
        <template #default="{ row }">
          <el-button
            class="but_text"
            text
            type="primary"
            @click="handleActive(row)"
          >
          激活账号
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <div v-if="has_more == 1" class="load-more">
      <el-button
        :loading="listLoading"
        style="font-size: 16px; font-weight: bold"
        text
        type="primary"
        @click="loadMore"
      >
        点击加载更多
      </el-button>
    </div>
    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { useTabsStore } from '@/store/modules/tabs'
  import { handleActivePath } from '@/utils/routes'
  import { getOrderCodeList } from '@/api/enterpriseWeChat/orderCode'
  import VabDraggable from 'vuedraggable'
  import { Delete, Plus, Search, Setting } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'OrderCodeList',
    components: {
      Edit: defineAsyncComponent(() => import('./components/TableEdit')),
      VabDraggable,
    },
    setup() {
      const route = useRoute()
      const router = useRouter()
      const tabsStore = useTabsStore()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const $baseTableHeight = inject('$baseTableHeight')
      const { changeTabsMeta, delVisitedRoute } = tabsStore

      const state = reactive({
        value: '1',
        editRef: null,
        border: true,
        height: $baseTableHeight(1),
        stripe: true,
        lineHeight: 'default',
        checkList: ['激活码', '激活码类型', '是否使用'],
        columns: [
          {
            label: '激活码',
            prop: 'active_code',
          },
          {
            label: '激活码类型',
            prop: 'type',
          },
          {
            label: '是否使用',
            prop: 'is_use',
          },
        ],
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        title: '',
        has_more: 0,
        queryForm: {
          corp_id: null,
          order_id: null,
          next_cursor: null,
        },
      })

      const dragOptions = computed(() => {
        return {
          animation: 600,
          group: 'description',
        }
      })
      const finallyColumns = computed(() => {
        return state.columns.filter((item) =>
          state.checkList.includes(item.label)
        )
      })

      const fetchData = async () => {
        state.listLoading = true
        const { data } = await getOrderCodeList(state.queryForm)
        console.log(data)
        if (data.order_list) {
          state.list = [...state.list, ...data.code_list]
          state.has_more = data.has_more
          if (data.has_more == 1) {
            state.queryForm.next_cursor = data.next_cursor
          }
        }
        state.listLoading = false
      }

      const containerRef = ref(null)
      const { toggle, isFullscreen } = useFullscreen(containerRef)
      const clickFullScreen = () => {
        toggle().then(() => {
          handleHeight()
        })
      }
      const handleHeight = () => {
        if (isFullscreen.value) state.height = $baseTableHeight(1) + 356
        else state.height = $baseTableHeight(1)
      }
      const handleActive = (row) => {
        console.log(row)
        if (row.active_code) {
          state['editRef'].showEdit(state.queryForm.corp_id, row.active_code)
        }
      }
      const goBack = async () => {
        const detailPath = await handleActivePath(route, true)
        await router.push('/enterpriseWeChat/orderList')
        await delVisitedRoute(detailPath)
      }
      onMounted(() => {
        changeTabsMeta({
          title: '激活码列表',
          meta: {
            title: `${route.query.corp_name} 激活码列表`,
          },
        })
        state.title = route.query.corp_name
        state.queryForm.corp_id = route.query.corp_id
        state.queryForm.order_id = route.query.order_id
        fetchData()
      })

      return {
        ...toRefs(state),
        dragOptions,
        containerRef,
        isFullscreen,
        finallyColumns,
        handleHeight,
        clickFullScreen,
        fetchData,
        handleActive,
        Plus,
        Delete,
        Search,
        Setting,
        goBack,
      }
    },
  })
</script>
<style lang="scss" scoped>
  @use 'sass:math';
  .load-more {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
  }
  .custom-table-container {
    :deep() {
      i {
        cursor: pointer;
      }
    }

    .right-panel {
      .stripe-panel,
      .border-panel {
        margin: 0 10px #{math.div($base-margin, 2)} 10px !important;

        :deep() {
          .el-checkbox__label {
            margin-left: 0 !important;
          }
        }
      }

      [class*='ri'] {
        font-size: $base-font-size-big;
        color: var(--el-color-black);
      }
    }
  }
</style>
<style lang="scss">
  html body .custom-table-checkbox {
    [class*='ri'] {
      vertical-align: -0.5px !important;
      cursor: pointer;
    }

    .el-checkbox {
      margin: 5px 0 5px 8px;
    }
  }

  .custom-table-radio {
    width: 240px !important;
  }
</style>
